from presenter import basepresenter
from domain import userprofile

class RegisterPresenter(basepresenter.BasePresenter):

    def respondToGet(self):

        if not self.currentuser:
            self.view.redirectToUrl(self.template_values['loginurl'])
        else:
            self.showForm()

    def respondToPost(self):
        if not self.currentuser:
            self.view.redirectToUrl(self.template_values['loginurl'])
        else:
            # see if the name is in use
            if (self.userprofiletask.isNicknameInUse(self.request.get('nickname'))):
                # send the user back to the form, with error message
                self.template_values['error_message'] = ['Nickname is already in use']
                self.showForm()
                return

            # populate an article object from the request
            newuserprofile = userprofile.UserProfile(nickname=self.request.get('nickname'), googleuser=self.currentuser, enabled=True)

            # validate the user profile
            if (newuserprofile.isValid()):
                # create the task and save the article
                self.userprofiletask.save(newuserprofile)

                #send the user to the home page
                self.view.redirectToUrl('/')
            else:
                #send the user back to the form, with errors
                self.template_values['error_message'] = newuserprofile.errormessage
                self.showForm()


    def showForm(self):
        page_title = self.sitetitle + ' - Register As A Member'
        self.template_values['page_title'] = page_title
        self.view.showGetResponse(self.template_values)